//
//  FileController.swift
//  Template
//
//  Created by zhibao on 2024/2/1.
//

import UIKit

class FileController: SecSuperController,UITableViewDelegate,UITableViewDataSource,DataChangeDelegate,UIDocumentInteractionControllerDelegate,UIDocumentPickerDelegate,TZImagePickerControllerDelegate {
    var from:SelectFileFrom = .TQbz
    var againFlag = false
    var selectArrayBlock:selectReturnBlock?
    
    //顶部按钮集合
    fileprivate var btns = Array<UIButton>()
    
    fileprivate var dataArray = [[String:String]]()
    fileprivate var selectIndex = 0
    
    fileprivate var addBtn:UIButton!
    
    fileprivate var document:UIDocumentInteractionController!
    fileprivate var showTableView:MYTableView!
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.getListData()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        let topView = UIView(frame: CGRectMake(0, 0, 260, 40))
        self.gk_navigationBar.addSubview(topView)
        topView.bottom = self.gk_navigationBar.height
        topView.centerX = self.gk_navigationBar.width / 2
        for i in 0 ..< 2 {
            let btn = UIButton(type: .custom)
            btn.frame = CGRectMake(CGFloat(130 * i), 0, 130, 40)
            btn.setTitle("导入文件", for: .normal)
            btn.setTitleColor(UIColor.white, for: .normal)
            btn.setImage(UIImage(systemName: "scope"), for: .normal)
            btn.titleLabel?.font = MY_SCALE_SemiboldFONT(16)
            btn.tag = 1000 + i;
            btn.addTarget(self, action: #selector(topBtnClick(sender:)), for: .touchUpInside)
            
            topView.addSubview(btn)
            btn.setButtonImageAlignmentStyle(.bottom, imageAndLabelSpace: 4)
            if(i == 1){
                btn.setTitle("生成作品", for: .normal)
                btn.setTitleColor(MYColor.color(withHexString: "#878989"), for: .normal)
                btn.setImage(nil, for: .normal)
            }
            btns.append(btn)
        }
        self.initTableView()
    }
    
    @objc func topBtnClick(sender :UIButton) {
        for btn in btns {
            btn.setTitleColor(MYColor.color(withHexString: "#878989"), for: .normal)
            btn.setImage(nil, for: .normal)
        }
        sender.setTitleColor(UIColor.white, for: .normal)
        sender.setImage(UIImage(systemName: "scope"), for: .normal)
        
        if(sender.tag == 1000){
            addBtn.isHidden = false
            selectIndex = 0
        }else{
            addBtn.isHidden = true
            selectIndex = 1
        }
        self.getListData();
    }
    
    func initTableView() {
        showTableView = MYTableView(frame: CGRectMake(0, navigationFullHeight(), SCREEN_WIDTH, SCREEN_HEIGHT - tabBarFullHeight() - navigationFullHeight()), style: .plain)
        showTableView.delegate = self
        showTableView.dataSource = self
        showTableView.dataChangeDelegate = self
        showTableView.separatorStyle = .none
        showTableView.register(SelectFileCell.self, forCellReuseIdentifier: "SelectFileCell")
        self.view.addSubview(showTableView)
        showTableView.noDataType = .TableViewNoDataType_FILE
        showTableView.mj_footer?.endRefreshingWithNoMoreData()
        
        addBtn = UIButton(type: .custom)
        addBtn.setImage(UIImage(systemName: "plus"), for: .normal)
        addBtn.tintColor = UIColor.white
        addBtn.backgroundColor = MYBlue
        addBtn.layer.cornerRadius = 30;
        addBtn.addTarget(self, action: #selector(addClick), for: .touchUpInside)
        self.view.addSubview(addBtn)
        addBtn.snp.makeConstraints { make in
            make.right.equalTo(-20)
            make.bottom.equalTo(showTableView.snp.bottom).offset(-10)
            make.width.height.equalTo(60)
        }
        self.getListData()
    }
    
    @objc func addClick() {
        Helper.alertAddToApp { index in
            if index == 1000 {
                let documentType = ["public.audio",
                                    "public.movie",
                ]
                let documentPicker = UIDocumentPickerViewController(documentTypes: documentType, in: .open)
                documentPicker.delegate = self
                documentPicker.allowsMultipleSelection = false
                documentPicker.modalPresentationStyle = .fullScreen
                self.navigationController?.present(documentPicker, animated: true, completion: {
                    
                })
            }else if index == 1001 {
                
                let imagePickerVc = TZImagePickerController(maxImagesCount: 9, delegate: self)
                imagePickerVc?.naviTitleColor = UIColor.white
                imagePickerVc?.barItemTextColor = UIColor.white
                imagePickerVc?.statusBarStyle = .lightContent
                imagePickerVc?.allowPickingVideo = true
                imagePickerVc?.allowTakeVideo = true
                imagePickerVc?.allowTakePicture = false
                imagePickerVc?.allowPickingImage = false
                imagePickerVc?.allowPickingMultipleVideo = false
                imagePickerVc?.allowEditVideo = true
                imagePickerVc?.allowPickingOriginalPhoto = false
                imagePickerVc?.didFinishPickingAndEditingVideoHandle = {
                    coverImage,outputPath,errorMsg in
                    DLog(message: "\(String(describing: outputPath))")
//                    FmpegTools.change(with: outputPath ?? "", withDoucm: IMPORTAUDIOSTYPE, withNewName: "", withSaveType: "wav") { result in
//                        if result == 0 {
//                            QMUITips.showSucceed("导入成功")
//                            self.getListData()
//                            self.showTableView.reloadData()
//                        }else{
//                            QMUITips.showError("导入失败")
//                        }
//                    }
                }
                imagePickerVc!.modalPresentationStyle = .fullScreen
                self.navigationController?.present(imagePickerVc!, animated: true, completion: {
                    
                })
            }
        }
    }
    
    func getListData(){
        var type = IMPORTAUDIOSTYPE
        if(selectIndex == 1){
            type = CREATEAUDIOSTYPE
        }
        let tempData = Helper.getData(type)
        dataArray = tempData!["data"] as! [[String:String]]
        self.showTableView.reloadData()
    }
}
extension FileController{
    
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        DLog(message: "urls==\(urls)")
        if urls.count < 1{
            return
        }
        
        for url in urls {
            let flag =  url.startAccessingSecurityScopedResource()
            if(flag){
                let fileName = url.lastPathComponent
                if(fileName.contains(".pcm") ||
                   fileName.contains(".mp4") ||
                   fileName.contains(".avi") ||
                   fileName.contains(".mov") ||
                   fileName.contains(".wmv") ||
                   fileName.contains(".mpeg") ||
                   fileName.contains(".m4v") ||
                   fileName.contains(".flv")
                ){
                    QMUITips.showLoading("传入中", detailText: "...请耐心等待...", in: self.view)
//                    FmpegTools.change(with: url.absoluteString, withDoucm: IMPORTAUDIOSTYPE, withNewName: "", withSaveType: "wav") { result in
//                        QMUITips.hideAllTips()
//                        if(result == 0){
//                            QMUITips.showSucceed("传入成功", detailText: "感谢等待,请前往'文件'->‘本地文件’查看")
//                        }else{
//                            QMUITips.showError("传入失败", detailText: "视频格式暂时无法转码，请替换")
//                        }
//                    }
                }else if(fileName.contains(".wav") ||
                         fileName.contains(".aiff") ||
                         fileName.contains(".flac") ||
                         fileName.contains(".m4a") ||
                         fileName.contains(".alac") ||
                         fileName.contains(".wma") ||
                         fileName.contains(".mp3") ||
                         fileName.contains(".ogg") ||
                         fileName.contains(".aac") ||
                         fileName.contains(".wma")
                ){
                    Helper.saveData([url,fileName], withDocum: IMPORTAUDIOSTYPE, withType: DOCUMENTYPE)
                    QMUITips.showSucceed("传入成功", detailText: "感谢等待,请前往'文件'->‘本地文件’查看")
                }else{
                    QMUITips.showError("传入失败", detailText: "只能上传wav/aiff/flac/alac/wma/mp3/ogg/aac/wma/m4a")
                }
            }
            url.stopAccessingSecurityScopedResource()
        }
        self.getListData()
    }
    
}
extension FileController{
    func refreshData(withTabelViewTag tableViewTag: Int) {
        self.getListData()
    }
    
    func loadMoreData(withTabelViewTag tableViewTag: Int) {
        self.getListData()
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let modeDic = dataArray[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "SelectFileCell") as! SelectFileCell
        cell.updata(dic: modeDic, selectType: .Normal)
        cell.dealBlock = {
            QMUITips.show(withText: "...开发中...", detailText: "敬请期待")
//            self.dealAudio(modeDic)
        }
        return cell
    }
    
    func dealAudio(_ dic:[String:Any]) {
        let bgView = UIView(frame: CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT))
        bgView.backgroundColor = MYColor.color(withHexString: "#010811", alpha: 0.6)
        UIApplication.shared.delegate!.window!!.addSubview(bgView)
        let contentView = UIView(frame: CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 695 + 15))
        contentView.backgroundColor = MYColor.color(withHexString: "f9f9f9")
        contentView.layer.cornerRadius = 15
        bgView.addSubview(contentView)
        
        let topCancalBtn = UIButton(type: .custom)
        bgView.addSubview(topCancalBtn)
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let modeDic = dataArray[indexPath.row]
        let commPlayerControllr = CommPlayerController()
        commPlayerControllr.na_title = modeDic["text"] ?? ""
        commPlayerControllr.partUrl = modeDic["url"] ?? ""
        let lastPath = "/\(modeDic["type"]!)/\(modeDic["url"]!)"
        commPlayerControllr.url = Helper.getPath()!.appending(lastPath)
        commPlayerControllr.threeType = AUDIOSTYPE
        commPlayerControllr.docum = modeDic["type"] ?? ""
        commPlayerControllr.type = .localMp3
        self.navigationController?.pushViewController(commPlayerControllr, animated: true)
    }
    
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let dic = dataArray[indexPath.row]
        let reNameAction = UIContextualAction(style: .normal, title: "重命名") { (action, view, completed)  -> Void in
            Helper.alertShow(withTitle: "重命名", withSureBtnTitle: "确定", withCancelBtnTitle: "取消") { newName in
                if (newName!.qmui_trimAllWhiteSpace.count > 0){
                    for temDic in self.dataArray {
                        
                        if newName!.qmui_trimAllWhiteSpace == temDic["text"] {
                            QMUITips.showError("友情提示", detailText: "名称重复")
                            return
                        }
                    }
                    Helper.rename(withUrl: dic["url"], withNewName: newName!.qmui_trimAllWhiteSpace , withDocum: dic["type"], withType: DOCUMENTYPE)
                    self.getListData()
                }
            }
        }
        reNameAction.backgroundColor = MYColor.color(withHexString: "#1AB8A6")
        
        let deleteAction = UIContextualAction(style: .normal, title: "删除") { (action, view, completed)  -> Void in
            Helper.alertShow(withTitle: "是否删除？", withContent: "", withSureBtnTitle: "确定", withCancelBtnTitle: "取消") { selectIndex in
                if(selectIndex == 1){
                    Helper.deleUrl(dic["url"], withDocum: dic["type"], withType: DOCUMENTYPE)
                }
                self.getListData()
            }
        }
        deleteAction.backgroundColor = MYColor.color(withHexString: "#FC2F55")
        
        let config = UISwipeActionsConfiguration(actions: [deleteAction,reNameAction])
        config.performsFirstActionWithFullSwipe = false
        return config
    }
}

